const Sequelize = require('sequelize')
const Op = Sequelize.Op;

module.exports = (sequelize, DataTypes ) => {

  class m_Topic extends Sequelize.Model {

    static getHomeRecommendation(pars){
      var [page = 1, pagesize = 12, order='ASC',orderBy='sort'] = [pars.page, pars.pagesize,pars.order,pars.orderBy]
      let condition = {
          attributes: ['id', 'name', 'thumbnail', 'tp_type', 'status', 'sort', 'create_time','link','position','watch_num','page_thumbnail'],
          raw: true,
          offset: pagesize * (page - 1),
          limit: parseInt(pagesize)
      }
      var where={
          position:1,
          status:0
      }
      condition.where=where
      condition["order"] = [
          [orderBy, order]
      ]
      return this.findAll(condition)
    }

    //获取专题 
    static async getTopics(pars) {
      var querydata = []
      var [page = 1, pagesize = 15, limit = 0] = [pars.page, pars.pagesize, pars.limit]
      let condition = {
          attributes: ['id', 'name', 'thumbnail', 'tp_type', 'status', 'title','sort', 'create_time','link','position','watch_num','page_thumbnail'],
          raw: true,
          offset: pagesize * (page - 1),
          limit: parseInt(pagesize)
      }
      condition.order = [
          ['sort', 'ASC']
      ]
      querydata = await this.findAndCountAll(condition)
      return querydata;
  }
    //获取列表条数，用于添加排序
    static async getTopicCount(){
      let result=await this.count()
      return result;
    }

    /**
     * @author: xgq
     * @description: 
     * @param {type} 
     * @return: 
     */        
    static async getTopicByIdOrName(param) {
        let querydata = []
        querydata = await this.findAll({ 
            where: {
                [Op.or]:[{id:param},{name:{[Op.like]:`%${param}%`}}]
            }
        })
        return querydata;
    }


    // 拽动排序
    static async topicSort(params) {
      var queryData = []
      var valueArr = []
    //   let sql = `select id,sort from topic order by sort asc`
    //   queryData = await this.raw(sql)
      queryData=await this.findAll({attributes:['id','sort'],order:[['sort', 'ASC']]})
      //start拖动的目的地
      //end从哪一行开始拖动的
      //start《end从后往前拖动   start》end从前往后拖动
      if (parseInt(params.start) < parseInt(params.end)) {//从后往前拖动
          for (var i = parseInt(params.start); i <= parseInt(params.end); i++) {
              console.log(i == parseInt(params.end))
              if (i == parseInt(params.end)) {
                  var value = {
                      id: queryData[i].id,
                      sort: parseInt(params.start) + 1
                  };
              } else {
                  var value = {
                      id: queryData[i].id,
                      sort: queryData[i].sort + 1,
                  };
              }

              valueArr.push(value)
          }
      } else if (parseInt(params.start) > parseInt(params.end)) {//从前往后拖动
          for (var i = parseInt(params.end); i <= parseInt(params.start); i++) {
              if (i == parseInt(params.end)) {
                  var value = {
                      id: queryData[i].id,
                      sort: parseInt(params.start) + 1
                  }
              } else {
                  var value = {
                      id: queryData[i].id,
                      sort: queryData[i].sort - 1,
                  };
              }

              valueArr.push(value)
          }
      }
      var updateData = []
      updateData = await this.bulkCreate(valueArr, { updateOnDuplicate: ["sort"] });
      return updateData
    }

    // 修改专题状态
    static async alterTopicStatus(pars){
      let {id,status}=pars;
      let result=await this.update({status},{where:{id}})
      return result;
    }


    static async fornt_homeRecommendation(pars){
      var querydata = []
      var [page = 1, pagesize = 12, limit = 0,order='ASC',orderBy='sort'] = [pars.page, pars.pagesize, pars.limit,pars.order,pars.orderBy]
      let condition = {
          attributes: ['id', 'name', 'thumbnail', 'tp_type', 'status', 'sort', 'create_time','link','position','watch_num','page_thumbnail'],
          raw: true,
          offset: pagesize * (page - 1),
          limit: parseInt(pagesize)
      }
      var where={
          position:1,
          status:0
      }
      condition.where=where
      condition["order"] = [
          [orderBy, order]
      ]
      querydata = await this.query(condition)
      return querydata;
    }

  
    static async getTopicById(id) {
        let querydata = []
        querydata = await this.findOne({ 
            where: {
                id
            },
            raw:true
        })
        return querydata;
    }

  }
  
  m_Topic.init({
    // attributes
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    name: { type: DataTypes.STRING(45) },
    thumbnail: { type: DataTypes.STRING(255) },
    page_thumbnail:{ type: DataTypes.STRING(255) },
    tp_type: { type: DataTypes.INTEGER(4), defaultValue:0 },
    status: { type: DataTypes.INTEGER(1) },
    sort: { type: DataTypes.INTEGER(4) },
    link:{type: DataTypes.STRING(255)},
    create_time: { type: DataTypes.INTEGER },
    position: { type: DataTypes.INTEGER(1) },
    watch_num: { type: DataTypes.INTEGER },
    title: { type: DataTypes.STRING(800) },
  }, {
    sequelize,
    modelName: 'topic',
    freezeTableName: true,
    timestamps: false
  });

  return m_Topic;
}